package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    public TurnoverReportVO turnoverReport(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(startDate);
        while (startDate.isBefore(endDate)) {
            startDate = startDate.plusDays(1);
            dateList.add(startDate);
        }
        String join = StringUtils.join(dateList, ",");

        List<Double> sumList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = date.atTime(LocalTime.MIN);
            LocalDateTime endTime = date.atTime(LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            // 如果没有营业额，设置为0
            if (turnover == null) {
                turnover = 0.0;
            }
            sumList.add(turnover);
        }
        String sum = StringUtils.join(sumList, ",");


        return TurnoverReportVO.builder().dateList(join).turnoverList(sum).build();


    }

    public UserReportVO userReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = date.atTime(LocalTime.MIN);
            LocalDateTime endTime = date.atTime(LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("end", endTime);
            Integer totalUser = userMapper.countByMap(map);
            map.put("begin", beginTime);
            Integer newUser = userMapper.countByMap(map);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO
                .builder()
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .dateList(StringUtils.join(dateList, ","))
                .build();
    }

    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalOrderList = new ArrayList<>();
        List<Integer> completedOrderList = new ArrayList<>();

        dateList.add(begin);
        while (begin.isBefore(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for(LocalDate date : dateList){
            LocalDateTime beginTime = date.atTime(LocalTime.MIN);
            LocalDateTime endTime = date.atTime(LocalTime.MAX);

            Map<String, Object> map = new HashMap<>();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            Integer total = orderMapper.countByMap(map);
            map.put("status", Orders.COMPLETED);
            Integer completed = orderMapper.countByMap(map);

            completedOrderList.add(completed);
            totalOrderList.add(total);
        }

        Integer total = totalOrderList.stream().reduce(0,Integer::sum);
        Integer completed = completedOrderList.stream().reduce(0,Integer::sum);
        Double rate =0.0;
        //除法要考虑除数为0的情况
        if(total!=0){
            rate=completed * 1.0 / total;
        }

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(totalOrderList, ","))
                .validOrderCountList(StringUtils.join(completedOrderList, ","))
                .totalOrderCount(total)
                .validOrderCount(completed)
                .orderCompletionRate(rate)
                .build();
    }

    public SalesTop10ReportVO salesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = begin.atTime(LocalTime.MIN);
        LocalDateTime endTime = end.atTime(LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = orderMapper.querySalesTop10(beginTime, endTime);

        List<String> names= goodsSalesDTOS.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers= goodsSalesDTOS.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String nameStr = StringUtils.join(names, ",");
        String numberStr = StringUtils.join(numbers, ",");

        return SalesTop10ReportVO
                .builder()
                .nameList(nameStr)
                .numberList(numberStr)
                .build();
    }

    public void export(HttpServletResponse response){
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        LocalDateTime beginTime = begin.atStartOfDay();
        LocalDateTime endTime = end.atTime(LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);

        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //打开工作簿
            XSSFWorkbook workbook = new XSSFWorkbook(resourceAsStream);

            //获取第一个sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            //时间
            sheet.getRow(1).getCell(1).setCellValue("时间:"+begin+"至"+end);
            //营业额
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            //订单完成率
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            //新用户
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            //有效订单
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            //平均客单价
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            //每日明细表
            for(int i=0;i<30;i++){
                LocalDate date = begin.plusDays(i);
                LocalDateTime beginTime1 = date.atStartOfDay();
                LocalDateTime endTime1 = date.atTime(LocalTime.MAX);

                BusinessDataVO businessData = workspaceService.getBusinessData(beginTime1, endTime1);

                sheet.getRow(7+i).getCell(1).setCellValue(date.toString());
                sheet.getRow(7+i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7+i).getCell(5).setCellValue(businessData.getNewUsers());
                sheet.getRow(7+i).getCell(6).setCellValue(businessData.getOrderCompletionRate());
            }

            //下载文件到客户端
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);

            //关闭资源
            workbook.close();
            outputStream.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
